package cs.java.collections;

import java.util.Iterator;

import static cs.java.lang.Lang.unsuported;




public abstract class GenericIterator<T> implements Iteration<T> {
  private int index = -1;
  private boolean iteratingForward = true;
  private int iterationLength;

  public GenericIterator(int length) {
    this.iterationLength = length;
  }

  public int getIndex() {
    return index;
  }

  public boolean hasNext() {
    if (iteratingForward) return index < iterationLength - 1;
    return index > 0;
  }

  public Iterator<T> iterator() {
    return this;
  }

  public T next() {
    if (iteratingForward)
      ++index;
    else --index;
    return getValue();
  }

  public final void remove() {
    onRemove();
    index--;
    iterationLength--;
  }

  public Iteration<T> reverse() {
    this.iteratingForward = false;
    index = iterationLength;
    return this;
  }

  public Iteration<T> skip(int length) {
    if (iteratingForward)
      index += length;
    else index -= length;
    return this;
  }

  protected abstract T getValue();

  protected void onRemove() {
    throw unsuported();
  }
}